package com.shaozi.nc.data.mongodao;

import java.util.List;

import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import com.shaozi.data.mongo.dao.BaseMongoDaoImpl;
import com.shaozi.data.mq.business.base.MqConsts;
import com.shaozi.nc.data.model.OrgPushMsgModel;

@Repository("orgPushMsgMDao")
public class OrgPushMsgMDao extends BaseMongoDaoImpl {
	private final Logger logger = Logger.getLogger(OrgPushMsgMDao.class);
	@Autowired
	private MongoTemplate shaoziTemplate;

	public OrgPushMsgMDao() {

	}

	public String addOrgPushMsg(String compId, OrgPushMsgModel model) {
		model.setIsDel(0);
		model.setCreateTime(System.currentTimeMillis());
		shaoziTemplate.save(model, getCollectionName(compId));
		return model.getId();
	}

	public OrgPushMsgModel upsertByUnique(String compId, OrgPushMsgModel newModel) {
		Criteria c = new Criteria("sourceType").is(newModel.getSourceType());
		c.and("levelType").is(newModel.getLevelType());
		c.and("isDel").is(0);
		switch (newModel.getLevelType()) {
		case MqConsts.LevelType.Comp:
			c.and("compId").is(newModel.getCompId());
			break;
		case MqConsts.LevelType.Org:
			c.and("orgId").is(newModel.getOrgId());
			break;
		case MqConsts.LevelType.User:
			c.and("userId").is(newModel.getUserId());
			break;
		default:
			logger.warn("upsert fail,compId=" + compId + ";model=" + newModel.toJsonStr());
			return null;
		}
		Query query = new Query(c);
		OrgPushMsgModel m = shaoziTemplate.findOne(query, OrgPushMsgModel.class, getCollectionName(compId));
		if (m == null) {
			newModel.setIsDel(0);
			newModel.setCreateTime(System.currentTimeMillis());
		} else {
			newModel.setId(m.getId());
		}
		shaoziTemplate.save(newModel, getCollectionName(compId));
		return newModel;
	}

	public List<OrgPushMsgModel> loadAll(String compId, int skip, int limit) {
		Criteria c = new Criteria("isDel").is(0);
		Query query = new Query(c);
		query.skip(skip);
		query.limit(limit);
		return shaoziTemplate.find(query, OrgPushMsgModel.class, getCollectionName(compId));
	}

	public OrgPushMsgModel getByCompId(String compId) {
		Criteria c = new Criteria("levelType").is(MqConsts.LevelType.Comp);
		c.and("isDel").is(0);
		Query query = new Query(c);
		return shaoziTemplate.findOne(query, OrgPushMsgModel.class, getCollectionName(compId));
	}

	public OrgPushMsgModel getById(String compId, String _id) {
		Criteria c = new Criteria("_id").is(new ObjectId(_id));
		c.and("isDel").is(0);
		Query query = new Query(c);
		return shaoziTemplate.findOne(query, OrgPushMsgModel.class, getCollectionName(compId));
	}

	private String getCollectionName(String compId) {
		return String.format("%s_%s", "nc_org_push_msg", compId);
	}
}
